import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_update/azhon_app_update.dart';
import 'package:flutter_app_update/update_model.dart';

class Upgrade extends StatefulWidget {
  bool forcedUpgrade;
  String url;
  String des;
  String appId;

  Upgrade(this.forcedUpgrade, this.url, this.des, this.appId, {super.key});

  @override
  State<StatefulWidget> createState() {
    return _UpgrageState();
  }
}

class _UpgrageState extends State<Upgrade> {
  var dio = Dio();

  @override
  void initState() {
    super.initState();
    AzhonAppUpdate.listener((map) {
      print(map['type']);
    });
    Future.delayed(Duration.zero, () {
      _showUpdateDialog(widget.forcedUpgrade, widget.url, widget.des);
    });
    // _checkVersion();
  }


  // void _checkVersion() async {
  //   dio.options.headers = {"deviceId": widget.deviceId};
  //   var response = await dio.post(
  //       "https://oapi.jarvisgo.cn/pos/posTerminal/findUpdateVersion",
  //       data: {"build_number": widget.buildNumber, "app_id": widget.appId});
  //   final forcedUpgrade = response.data["data"]["force"];
  //   final url = response.data["data"]["update_url"];
  //   final des = response.data["data"]["change_log"];
  //   _showUpdateDialog(!forcedUpgrade, url, des);
  // }

  _showUpdateDialog(bool forcedUpgrade, String url, String des) {
    showDialog(
      context: context,
      barrierDismissible: !forcedUpgrade,
      builder: (BuildContext context) {
        return PopScope(
          canPop: !forcedUpgrade,
          child: AlertDialog(
            title: const Text('发现新版本'),
            content: Text(des),
            actions: <Widget>[
              if (!forcedUpgrade)
                TextButton(
                  child: const Text('取消'),
                  onPressed: () => {
                    Navigator.of(context).pop(),
                  },
                ),
              TextButton(
                child: const Text('升级'),
                onPressed: () {
                  _appUpdate(url);
                  if (!forcedUpgrade) {
                    Navigator.of(context).pop();
                  }
                },
              ),
            ],
          ),
        );
      },
    ).then((value) => Navigator.of(context).pop());
  }

  _appUpdate(String url) {
    UpdateModel model = UpdateModel(
      url,
      "${widget.appId}.apk",
      "ic_launcher",
      'https://itunes.apple.com/cn/app/抖音/id1142110895',
    );
    AzhonAppUpdate.update(model).then((value) => debugPrint('$value'));
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: Colors.transparent,
    );
  }
}
